package org.example.demo.aqs.lock;

import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;

/**
 * 自己实现一个同步锁
 */
public class MyLock implements Lock {


    volatile AtomicReference<Thread> lock = new AtomicReference<>();

    volatile LinkedBlockingQueue<Thread> waitQueue = new LinkedBlockingQueue<>();


    @Override
    public void lock() {
        boolean isadd = false;
        // 如果获取不到锁，加入到等待队列中
        while(!tryLock()){
            if (!isadd){
                waitQueue.offer(Thread.currentThread());
                isadd = true;
            }
            // 使当前线程挂起，建议使用 while(!tryLock())，多次使用，防止伪唤醒
            LockSupport.park();
        }
        // 如果当前线程获取到锁了，移除等待队列
        waitQueue.remove(Thread.currentThread());
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }


    @Override
    public boolean tryLock() {
        return lock.compareAndSet(null,Thread.currentThread());
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        // 释放锁
        if(lock.compareAndSet(Thread.currentThread(),null)){
            // 释放成功后，等待队列中的任务需要全部唤醒
            Iterator<Thread> iterator = waitQueue.iterator();
            while (iterator.hasNext()){
                Thread next = iterator.next();
                LockSupport.unpark(next);
            }
        }
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
